#!/bin/bash

#replace the path below with your ndk-dir
#NDK=/Users/wangyang/android_dev/android-ndk

if [[ "$NDK" == "" ]]; then
    if command -v ndk-build; then
        export $NDK=$(command -v ndk-build)
    elif command -v ndk-build.cmd; then
        export $NDK=$(command -v ndk-build.cmd)
    else
        if ! command -v cmd; then
            function cmd() {
                if [[ -f "/mnt/c/Windows/system32/cmd.exe" ]]; then
                    /mnt/c/Windows/system32/cmd.exe $@
                fi
            }
        fi

        echo "command -v cmd=$(command -v cmd)"

        if [[ -z "$(command -v cmd &>/dev/null && cmd /C set | grep -i 'NDK')" ]]; then
            echo "Please specify the NDK variable to your ndk-dir"
            exit
        fi
    fi
fi

cd "$(dirname "$0")"

while [[ $# -gt 0 ]]; do
    PARSE_KEY="$1"
    case "$PARSE_KEY" in
    -r | --release)
        export CGE_RELEASE_MODE=1
        echo "release mode enabled!"
        shift
        ;;
    -d | --debug)
        export CGE_DEBUG_MODE=1
        echo "debug mode enabled!"
        shift
        ;;
    -b | -B)
        BUILD_ARG=-B
        echo "force rebuild!"
        shift
        ;;
    --disable-video-module)
        export CGE_NO_VIDEO_MODULE=1
        shift
        ;;

    esac

done

if [[ -z "$CGE_NO_VIDEO_MODULE" ]]; then
    export CGE_USE_VIDEO_MODULE=1
    export CGE_VIDEO_MODULEDEFINE="CGE_USE_VIDEO_MODULE=1"
fi

echo "The NDK dir is: ${NDK}, If the shell can not run normally, you should set the NDK variable to your local ndk-dir"

THREADS=$(getconf _NPROCESSORS_ONLN)
if [[ -z "$THREADS" ]] || [[ "$THREADS" -eq "0" ]]; then
    THREADS=8
fi

if [[ -n "$NDK" ]] && [[ -f "$NDK/ndk-build" ]]; then
    if ! "$NDK/ndk-build" ${BUILD_ARG} -j${THREADS}; then
        # check if using mac m1.
        if [[ $(uname -s) == "Darwin" ]] && uname -a | grep -i arm64; then
            arch -arch x86_64 "$NDK/ndk-build" ${BUILD_ARG} -j${THREADS}
        fi
    fi
elif [[ -n $(command -v cmd && cmd /C set | grep -i 'NDK') ]]; then
    cmd /C "set $CGE_VIDEO_MODULEDEFINE && %NDK%/ndk-build.cmd" ${BUILD_ARG} -j${THREADS}
else
    echo "Can not find NDK!"
fi
